package com.code.qgjx.controller.dealcontroller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.User;
import com.code.qgjx.service.UserService;
import com.code.qgjx.tools.MyTool;
import cn.hutool.crypto.SecureUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/Sys")
public class LoginResgisterDeal {

    @Autowired
    private UserService userService;

    /**
     * 处理用户登录请求
     *
     * @param username 用户名
     * @param password 明文密码
     * @param identify 用户身份标识
     * @param httpSession HTTP会话
     * @return 登录结果，成功返回用户信息，失败返回"fail"
     */
    @ResponseBody
    @RequestMapping(value = "/dealLogin")
    public String login(@RequestParam(value = "num") String username,
                        @RequestParam(value = "psw") String password,
                        @RequestParam(value = "identify") String identify,
                        HttpSession httpSession) {
        // 根据identify设置对应的角色
        String role;
        switch (identify) {
            case "0":
                role = "ADMIN";
                break;
            case "1":
                role = "TEACHER";
                break;
            case "2":
                role = "STUDENT";
                break;
            default:
                return "fail";
        }

        // 使用MD5加密密码
        String encryptedPassword = SecureUtil.md5(password);

        // 调用统一的登录服务
        User user = userService.login(username, encryptedPassword);

        if (user != null && role.equals(user.getRole())) {
            // 设置session
            httpSession.setAttribute("account", user.getUsername());
            httpSession.setAttribute("name", user.getName());
            httpSession.setAttribute("role", role.toLowerCase());
            httpSession.setAttribute("id", user.getId());
            httpSession.setAttribute("photo", user.getPhoto());

            // 返回用户信息
            return JSON.toJSONString(user);
        }

        return "fail";
    }

    /**
     * 处理教师注册请求
     *
     * @param map 包含注册信息的映射
     * @return 注册结果，成功返回"success"，失败返回"failure"
     */
    @RequestMapping(value = "/registerTeaDeal")
    @ResponseBody
    public String registerTeacher(@RequestBody Map<String, Object> map) {
        User user = new User();
        user.setUsername(map.get("num").toString());
        user.setPassword(SecureUtil.md5(map.get("psw").toString()));
        user.setRole("TEACHER");
        user.setName(map.get("name").toString());
        user.setPhone(map.get("phone").toString());
        user.setEmail(map.get("email").toString());
        if (map.get("photo") != null) {
            user.setPhoto(map.get("photo").toString());
        }

        return userService.register(user) ? "success" : "failure";
    }

    /**
     * 处理图片上传请求
     *
     * @param file 要上传的图片文件
     * @param request HTTP请求
     * @return 包含上传结果的映射
     * @throws IllegalStateException 如果文件上传失败
     * @throws IOException 如果文件读写失败
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public @ResponseBody Object updatePersonal(@RequestParam("photo") MultipartFile file, HttpServletRequest request)
            throws IllegalStateException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        String name = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String imgAbsolutePath = MyTool.SaveImg(file, MyTool.getImg(), name);
        map.put("code", 0);
        map.put("message", "上传成功");
        map.put("data", name);
        return map;
    }

    /**
     * 根据ID获取用户信息
     *
     * @param id 用户ID
     * @return 包含用户信息或错误消息的映射
     */
    @RequestMapping(value = "/getUserById")
    @ResponseBody
    public Map<String, Object> getUserById(@RequestParam Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getUserById(id);
            if (user != null) {
                result.put("code", 0);
                result.put("data", user);
            } else {
                result.put("code", 1);
                result.put("msg", "用户不存在");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "获取用户信息失败");
        }
        return result;
    }
}
